<?php

namespace XWAM\Addon\PXCallSystem\Controller;

/**
 * 外呼任务策略控制器
 *
 * @author Alen
 * @since 1.0 2014-6-19 by sutroon
 */
class TaskStrategyController extends AppbaseController {

    /**
     * 显示项目列表
     * @since 1.0 2014-7-17 by sutroon
     */
    public function index() {    
        $M = M('tcti_task_strategy');
        // 查询条件
        if (!$this->isSuperAdmin) {
            $where['siteID'] = $this->loginData['siteID'];
        }
        $list = $M->where($where)->select();

        // 分页定义
        $tsid = I('tsid');
        if (!$tsid && $list) {
            $tsid = $list[0]['id'];
        }
        if (!$tsid) {
            $this->assign('is_empty',true);
            $this->display();
            exit;
        }
        $data = $M->find($tsid);
        if ($data && '10' != $data['outOper']) {
            $speedcontrol = $this->get_speed_control($tsid, $data['speedMode'], $data['speed'], $data['trunkName']);
            $this->assign('speedcontrol', $speedcontrol);
        }

        $this->assign('data', $data);
        $this->assign('tsid', $tsid);
        $this->assign('list', sofn_set_site_id_text($list));
        $this->assign('isSuperAdmin', $this->isSuperAdmin);
        $this->display();
    }

    public function info($tsid) {
        $data = M('tcti_task_strategy')->find($tsid);
        if ($data) {
            $i = 0;
            if ($this->isSuperAdmin) {
                $summary['租户ID'] = $data['siteID'];
            }
            $summary['中继名称'] = $data['trunkName'];
            $summary['显示号码'] = $data['callerNo'];
            $summary['录音标识'] = get_yesnoState_text($data['recState']);
            if (strpos(',1,2,3,4,5,6,', ',' . $data['outOper'] . ',') !== false) {
                $summary['放音文件'] = substr($data['music'], strpos($data['music'], '/') + 1);
            }
            if (strpos(',1,2,3,4,5,', ',' . $data['outOper'] . ',') !== false) {
                $summary['最大放音次数'] = $data['musicLimit'];
            }
            $summary['播放工号'] = ($data['sayExtension'] == '1' ? '是' : '否');
            $outoper = get_outOper_text($data['outOper']);
            if ($data['outOper'] == '1' && $data['outDefaultQueue']) {
                $outoper .= '(放音结束后无按键转队列' . $data['outDefaultQueue'] . ')';
            }
            if (strpos(',0,1,6,', ',' . $data['outOper'] . ',') !== false) {
                $outoper .= $data['outEcEnable'] == '1' ? ('(评价,评价语音:' . substr($data['outEcMusic'], strpos($data['outEcMusic'], '/') + 1) . ')') : ' ';
            }
            $outoper .= $data['outQueue'] . ' ' . $data['outParam'];
            $summary['呼通后操作'] = $outoper;
            $summary['呼叫超时时长'] = $data['answerExpireTime'] . '秒';
            $this->assign('summary', sofn_array_to_tableform($summary, 3, array('TABLE_ATTR' => 'class="strategy-info" cellpadding="0" cellspacing="0"')));
        }
        $this->display();
    }

    // 获取速度控件 2014-10-29 by sutroon
    // $this->get_speed_control($tsid, $data['speedMode'], $data['speed'], $data['trunkName'])
    private function get_speed_control($tsid, $speedMode, $speed, $trunkName) {
        $summary = '<span style="font-size:12px;">外呼速度:<em>(' . get_speedMode_text($speedMode) . ')';
        if ($speedMode == 'channel') {
            $regNumber = M('tcti_trunk')->where("account='" . $trunkName . "'")->getField('regNumber');
            if (!$regNumber) {
                return '中继有误!';
            }
            $select = '<select id="speed" data-update-url="' . AddonU('TaskStrategy/set_speed', 'speed=varspeed&id=' . $tsid) . '">';
            for ($i = 1; $i <= $regNumber; $i++) {
                $select .= "<option value='$i'" . ($i == $speed ? ' selected="selected"' : '') . ">$i</option>";
            }
            $select .= '</select>';
            $summary .= $select;
        } else {
            $summary .= '1:<input type="text" size="3" id="speed" value="' . $speed . '" data-update-url="' . AddonU('TaskStrategy/set_speed', 'speed=varspeed&id=' . $tsid) . '" />';
        }
        return $summary . '</em></span>';
    }

    public function get_strategy_json() {
        if ($this->isSuperAdmin) {
            if (I('siteID')) {
                $where['siteID'] = I('siteID');
            }
        } else {
            $where['siteID'] = $this->loginData['siteID'];
        }
        $data = M('tcti_task_strategy')->where($where)->field('id, name as text')->select();
        $this->ajaxReturn($data);
    }

    /**
     * 设置速度
     * @since 1.0 2014-10-6 by sutroon
     */
    public function set_speed() {
        $speed = I('speed');
        $id = I('id');
        if (!$id || !$speed) {
            $this->ajaxMsg(false, '参数有误');
        }
        $result = M('tcti_task_strategy')->where("id=$id")->setField('speed', $speed);
        $this->ajaxMsg($result, '设置{%}');
    }

    /**
     * 设置速度比例浮动
     * @since 1.0 2014-10-28 by sutroon
     */
    public function set_speedFloatingRate() {
        $speedFloatingRate = I('speedFloatingRate');
        $id = I('id');
        if (!$id || !$speedFloatingRate) {
            $this->ajaxMsg(false, '参数有误');
        }
        $result = M('tcti_task_strategy')->where("id=$id")->setField('speedFloatingRate', $speedFloatingRate);
        $this->ajaxMsg($result, '设置{%}');
    }

    /**
     * 显示项目编辑表单
     */
    public function item_edit($id = 0) {
        if ($id && is_numeric($id)) {
            $M = M('tcti_task_strategy');
            $where['id'] = I('id');
            $list = $M->where($where)->select();
            if (!$list) {
                $this->ajaxMsg(false, '策略不存在!', AddonU('TaskStrategy/index'));
            }
            $this->assign('data', $list[0]);
        } else {
            $this->assign('data', null);
        }
        $this->display();
    }

    /**
     * 保存项目
     * 0直接转队列     无语音 无次数 队列号下拉框outQueue,是否评价outEcEnable(评价语音下拉框outEcMusic,评价按键outEcKey)
     * 1按码转队列     有语音 有次数 按码-队列选择框outParam,放音文件music,最大放音次数musicLimit,,是否评价outEcEnable(评价语音下拉框outEcMusic,评价按键outEcKey)
     * 6放音转队列     有语音 无次数 队列号下拉框outQueue,放音文件music,outExp1Enable放音outExp1秒转队列,是否评价outEcEnable(评价语音下拉框outEcMusic,评价按键outEcKey)
     * 2按码转菜单     有语音 有次数 按码-菜单选择框outParam,放音文件music,最大放音次数musicLimit,是否评价outEcEnable(评价语音下拉框outEcMusic,评价按键outEcKey)
     * 3放音后挂机     有语音 有次数 放音文件music
     * 4留言后挂机     有语音 有次数 放音文件music,最大放音次数musicLimit
     * 5按码后挂机     有语音 有次数 放音文件music,最大放音次数musicLimit
     * ====已弃用====
     * 7直接转队列评价 无语音 无次数 [合并到0]队列号下拉框outQueue,是否评价outEcEnable(评价语音下拉框outEcMusic,评价按键outEcKey)
     * 8按码转队列评价 有语音 有次数 [合并到1]按码-队列选择框outParam,放音文件music,最大放音次数musicLimit,是否评价outEcEnable(评价语音下拉框outEcMusic,评价按键outEcKey)
     * 9放音转队列评价 有语音 无次数 [合并到6]放音-队列下拉框outParam,outExp1Enable放音outExp1秒转队列,放音文件music,是否评价outEcEnable(评价语音下拉框outEcMusic,评价按键outEcKey)
     */
    public function item_save() {
        $params = new \Org\Su\Params();
        $params->addParam('siteID', 'number', '租户未选择!');
        $params->addParam('name', 'require', '策略名称必须填写!');
        $params->addParam('trunkName', 'require', '中继名称必须填写!');
        $params->addParam('regMode', 'require', '中继注册模式无效!');
        $params->addParam('outOper', 'require', '呼通后操作必须填写!');
        $outOper = I('outOper');
        if ('10' != $outOper) {
            $params->addParam('speedMode', 'require', '外呼速度模式必须填写!');
            $params->addParam('speed', 'double', '外呼速度必需选择!');
            $params->addParam('recState', 'number', '录音标识必须选择!');
            $params->addParam('sayExtension', 'number', '播放工号标识必须选择!');
            $params->addParam('answerExpireTime', 'number', '振铃超时时长必须填写!');
        } else {
            $params->addData('speedMode', 'percent'); // 应答后外呼需把最大通道数填上，否则不会生效 (2015-7-27 SoChishun Added.)
        }
        if (strpos(',1,6,2,3,4,5,', ",$outOper,") !== false) {
            $params->addParam('music', 'require', '放音文件必须选择!');
        } else {
            $params->addData('music', '');
        }
        if (strpos(',1,2,3,4,5,', ",$outOper,") !== false) {
            $params->addParam('musicLimit', 'number', '最大放音次数必须填写!');
        } else {
            $params->addData('musicLimit', '');
        }
        if (strpos(',1,2,', ",$outOper,") !== false) {
            $params->addParam('outParam', 'require', '呼通后操作具体参数必须填写!');
        } else {
            $params->addData('outParam', '');
        }
        if ($outOper == '1' && I('outDefaultQueueEnable') == '1') {
            $params->addParam('outDefaultQueue', 'require', '放音结束后无按键转队列必需选择');
        } else {
            $params->addData('outDefaultQueue', '');
        }
        if (strpos(',0,6,10,', ",$outOper,") !== false) {
            $params->addParam('outQueue', 'require', '呼通后操作队列号必须选择!');
        } else {
            $params->addData('outQueue', '');
        }
        if (strpos(',0,1,6,', ",$outOper,") !== false) {
            $outEcEnable = I('outEcEnable');
            //$params->addParam('sayExtension', 'number', '播放工号标识必须选择!');
        } else {
            $outEcEnable = 0;
            //$params->addData('sayExtension', '0');
        }
        $params->addData('outEcEnable', $outEcEnable);
        if ($outEcEnable == '1') {
            $params->addParam('outEcMusic', 'require', '评价放音文件必须选择!');
            //$params->addParam('outEcKey', 'require', '评价按键必须填写!');
        } else {
            $params->addData('outEcMusic', '');
            //$params->addData('outEcKey', '');
        }
        $outExp1Enable = I('outExp1Enable');
        if ($outOper !== '6') {
            $outExp1Enable = 0;
        }
        $params->addData('outExp1Enable', $outExp1Enable);
        if ($outExp1Enable == '1') {
            $params->addParam('outExp1', 'require', '放音时长必须填写!');
        } else {
            $params->addData('outExp1', '');
        }
        $params->addParam('remark', 'require', '', true);
        $params->addParam('callerNo', 'require', '主叫号码必须填写!');

        if ($params->hasError()) {
            $this->ajaxMsg(false, $params->getError());
        }
        $id = I('id');
        $M = M('tcti_task_strategy');
        if ($id) {
            $where['id'] = $id;
            $result = $M->where($where)->save($params->getParams());
        } else {
            // 检测名称是否重复
            $name = I('name');
            $where['name'] = $name;
            if ($M->where($where)->count() > 0) {
                $this->ajaxMsg(false, '[' . $name . '] 已存在!');
            }
            $params->addData('createdTime', date('Y-m-d H:i:s'));
            $result = $M->add($params->getParams());
            $id = $result;
        }
        if ($result === false) {
            $this->ajaxMsg(false, '保存失败!');
        } else {
            $table = sofn_get_sharding_field('DB_CALLNUMBER') . 'tcti_call_number' . $id;
            AddonD('DbTable')->create_table('CALL_NUMBER', $table);
            $trunkName = I('trunkName');
            $M->execute("update $table set trunkName='$trunkName' where taskStrategyID=$id;");
            $this->ajaxMsg(true, '保存成功!');
        }
    }

    /**
     * 删除项目
     */
    public function item_delete($id = '') {
        if (!$id)
            $this->ajaxMsg(false, '编号丢失!');
        // 判断是否有任务,有则不能删除(必需把任务删了才能删除)
        if (M('tcti_task')->where(array('taskStrategyID' => $id))->count() > 0) {
            $this->ajaxMsg(false, '该策略下有任务,请先删除任务!');
        }
        $result = M('tcti_task_strategy')->delete($id);
        $table = sofn_get_sharding_field('DB_CALLNUMBER') . 'tcti_call_number' . $id;
        M()->execute('drop table if exists ' . $table);
        $this->ajaxMsg($result, '删除{%}!');
    }

}
